package org.wupuser.repository;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import org.wupuser.model.User;

import java.util.List;

@Repository
public interface UserRepository extends JpaRepository<User, String> {
	@Query(nativeQuery = true, value = "select * from user where is_deleted = 0")
	List<User> findAll();
	
	@Query(nativeQuery = true, value = "select * from user where username like CONCAT('%',:username,'%') and is_deleted = 0")
	List<User> findByUsernameLike(@Param("username") String username);
	
	@Query(nativeQuery = true, value = "select * from user where username = :username and is_deleted = 0")
	User findByUsername(@Param("username") String username);
	
	@Query(nativeQuery = true, value = "select * from user where id = :id and is_deleted = 0")
	User findUserById(@Param("id") String id);
	
	@Query(nativeQuery = true, value = "select * from user where email = :email and is_deleted = 0")
	User findByEmail(@Param("email") String email);
	
	@Transactional
	@Modifying
	@Query(nativeQuery = true, value = "insert into user(username, password, email, create_time, update_time, is_deleted) values( :#{#user.username}, :#{#user.password}, :#{#user.email}, :#{#user.createTime}, :#{#user.updateTime}, :#{#user.isDeleted})")
	void saveUser(@Param("user") User user);
	
	@Transactional
	@Modifying
	@Query(nativeQuery = true, value = "update user set update_time = :#{#user.updateTime}, password = :#{#user.password} where id = :#{#user.id}")
	void updatePassword(@Param("user") User user);
	
	@Transactional
	@Modifying
	@Query(nativeQuery = true, value = "update user set update_time = :#{#user.updateTime}, email = :#{#user.email} where id = :#{#user.id}")
	void updateEmail(@Param("user") User user);
	
	@Transactional
	@Modifying
	@Query(nativeQuery = true, value = "update user set update_time = :#{#user.updateTime},gender = #{#user.gender},signatrue = #{#user.signatrue} where id = :#{#user.id}")
	void updateInfo(@Param("user") User user);
	
	@Transactional
	@Modifying
	@Query(nativeQuery = true, value = "update user set update_time = :#{#user.updateTime},avatar = #{#user.avatar} where id = :#{#user.id}")
	void updateAvatar(@Param("user") User user);
	
	@Transactional
	@Modifying
	@Query(nativeQuery = true, value = "update user set update_time = :#{#user.updateTime},username = #{#user.username} where id = :#{#user.id}")
	void updateUsername(@Param("user") User user);
	
	@Transactional
	@Modifying
	@Query(nativeQuery = true, value = "update user set update_time = :#{#user.updateTime},is_deleted = 1 where id = :#{#user.id}")
	void deleteUser(@Param("user") User user);
}
